import 'dart:async';

import 'package:flutter/material.dart';
import 'package:lx_location_plugin/lx_location_plugin.dart';

class LocationScreen extends StatefulWidget {
  const LocationScreen({super.key});

  // route name for navigation
  static const String routeName = '/location_screen';

  @override
  _LocationScreenState createState() => _LocationScreenState();
}

class _LocationScreenState extends State<LocationScreen> with WidgetsBindingObserver {
  String _serviceStatus = "服务未启动";
  String _locationInfo = "等待位置更新...";
  StreamSubscription? _locationSubscription;

  List<String> locationHistory = [];

  String _lifecycleState = 'unknown';

  @override
  void initState() {
    super.initState();
    // 添加打印以确认订阅创建
    print("正在订阅位置更新流");
    _locationSubscription = LxLocationPlugin().locationUpdates.listen(
          (Map<String, dynamic> location) {
        print("收到位置更新: $location");
        setState(() {
          _locationInfo = "时间：${DateTime.now()} $_lifecycleState 纬度: ${location['latitude']}, 经度: ${location['longitude']}, 角度： ${location['bearing']}";
          locationHistory.add(_locationInfo);
        });
      },
      onError: (error) {
        print("位置更新流错误: $error");
      },
    );
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    print("取消位置更新订阅");
    _locationSubscription?.cancel();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    setState(() {
      _lifecycleState = state.toString();
    });

    // 根据生命周期状态执行逻辑
    switch (state) {
      case AppLifecycleState.resumed:
        print('App 进入前台 (resumed)');
        // 在这里处理应用回到前台的逻辑
        break;
      case AppLifecycleState.inactive:
        print('App 处于非活跃状态 (inactive)');
        // 过渡状态，例如弹出系统对话框时
        break;
      case AppLifecycleState.paused:
        print('App 进入后台 (paused)');
        // 在这里处理应用进入后台的逻辑
        break;
      case AppLifecycleState.detached:
        print('App 已脱离 (detached)');
        // 应用进程被杀死但仍在内存中
        break;
      default:
        print('未知状态: $state');
        // 处理其他未知状态
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter位置服务演示'),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            const Text(
              '位置服务状态:',
              style: TextStyle(fontSize: 20),
            ),
            Text(
              _serviceStatus,
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 20),
            const Text(
              '当前位置:',
              style: TextStyle(fontSize: 20),
            ),
            Text(
              _locationInfo,
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 30),
            ElevatedButton(
              onPressed: _startLocationService,
              child: const Text('启动位置服务'),
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: _stopLocationService,
              child: const Text('停止位置服务'),
            ),
            Expanded(child: ListView.builder(
              itemCount: locationHistory.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(locationHistory[index]),
                );
              },
            )),
          ],
        ),
      ),
    );
  }

  Future<void> _startLocationService() async {
    String? result = await LxLocationPlugin().startLocationService();
    setState(() {
      _serviceStatus = result ?? "启动位置服务失败";
    });
  }

  Future<void> _stopLocationService() async {
    String? result = await LxLocationPlugin().stopLocationService();
    setState(() {
      _serviceStatus = result ?? "停止位置服务失败";
    });
  }
}